// 构造+原型还是使用ES6类来写
function MyPromise(fn) {
  // console.log(fn)
  // Promise只有2各种状态 一种是 pending 还是一种终止状态 resolved rejected失败
  this.promiseStatus = 'pending'
  let RESOLVED = 'resolved'
  let REJECTED = 'rejected'
  this.Callbacks= [] // [{resolve: function () {}, reject: function (params) {}}, {}]
  this.resolveValue = null
  this.rejectValue = null
  // 实现核心啊部分
  // 定义resolve函数作为实参
  let resolveFn = (value) => {
    this.promiseStatus = RESOLVED
    this.resolveValue = value
    // console.log(this.resolveValue, value, 11112223333) // hello world, hello world, 11112223333
    // 遍历所有resolve然后依次调用
    for (let value of this.Callbacks) {
      value.resolve(this.resolveValue)
    }
  }
  let rejectFn = (value) => {
    this.promiseStatus = REJECTED
    this.rejectValue = value
    // 遍历所有reject然后依次调用
    for (let value of this.Callbacks) {
      value.reject(this.rejectValue)
    }
  }
  fn(resolveFn, rejectFn) // 函数调用过程传递的是实参
}
// 接下来实现then部分
MyPromise.prototype.then = function (resolve = new Function(), reject = new Function()) {
  // console.log(resolve, reject, 12345679) // () => console.log('成功了') () => console.log(`失败了`) 12345679
  if (this.promiseStatus === 'pending') {
    this.Callbacks.push({resolve, reject}) // [{resolve: resolve, reject: reject}]
    console.log(this.Callbacks)
  } else if (this.promiseStatus === 'resolved') {
    resolve && resolve(this.resolveValue)
  } else if (this.promiseStatus === 'rejected'){
    reject && reject(this.rejectValue)
  }
  // 一定要在then里的回调函数return一个新的promise对象，否则执行顺序将向上开始查找，直到找到最近的promise实
  return this // 真正操作这里不是return this这里只是演示链式编程
  // 这里最终应该return新的promise而不是this
  // return new MyPromise((resolve, reject) => {
  //   ......
  // })
}
var p = new MyPromise(function (resolve, reject) {
  // resolve reject是形参 
  // 这里使用定时器模拟一些异步操作比如ajax请求等...
  console.log(6666) // 会立即执行
  resolve('hello world')
  console.log(99999)
})
p
.then((res) => console.log('成功了', res), (err) => console.log(`失败了`, err))
.then(() => console.log('hahahhaha')) // 是不是函数调用 函数调用过程中传递测参数是实参
